
package Administracion;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.awt.Image;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author pato
 */
public final class ventas extends javax.swing.JInternalFrame {

    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    DefaultTableModel dtm;
    local_connection conexion;
    ResultSetMetaData rsm;
    int idUsuario;
    int codigo;
    /**
     * Creates new form ventas
     */
    public ventas(int code) {
        initComponents();
        codigo = code;
        jTable1.getColumnModel().getColumn(0).setMaxWidth(50);
        jTable1.getColumnModel().getColumn(1).setMaxWidth(50);
        jTextField1.setDocument(new LimitadorCaracteres());
        jTextField1.requestFocus();
        jTable2.getColumnModel().getColumn(0).setMaxWidth(40);
        jTable2.getColumnModel().getColumn(1).setMaxWidth(40);
        jTable2.getColumnModel().getColumn(2).setPreferredWidth(80);
        jTable2.getColumnModel().getColumn(4).setMaxWidth(50);
        jTable2.getColumnModel().getColumn(5).setMaxWidth(50);
        jTable2.getColumnModel().getColumn(6).setMaxWidth(50);
        jTable2.getColumnModel().getColumn(3).setMaxWidth(100);
        conexion = new local_connection();
        try {
            cn = local_connection.getconnect();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
        cargarDatos();
    }

    void cargarDatos() {
        dtm = (DefaultTableModel) this.jTable1.getModel();
        dtm.setRowCount(0);
        String como="";
        try {
            como = (jTextField1.getText().equals(""))?"":"and folio like "+jTextField1.getText();
           
            ps = (PreparedStatement) cn.prepareStatement( "select  folio, ticket, fecha, sucursal from venta where id_cliente = ? "+como+" order by fecha desc");
            ps.setInt(1,codigo);
            rs = ps.executeQuery();
            ArrayList<Object[]> data = new ArrayList<>();

            while (rs.next()) {
                Object[] rows = new Object[jTable1.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                data.add(rows);
            }


            for (int i = 0; i < data.size(); i++) {
                dtm.addRow(data.get(i));
            }

        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        vendedor = new javax.swing.JLabel();
        facturada = new javax.swing.JLabel();
        cliente = new javax.swing.JLabel();
        peso = new javax.swing.JLabel();
        neto = new javax.swing.JLabel();
        descuento = new javax.swing.JLabel();
        total = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();

        setClosable(true);
        setTitle("Ventas por cliente");

        jTextField1.setText(" ");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Folio", "Numero", "Fecha", "Sucursal"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTable1KeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel2.setText("Vendedor:");

        jLabel3.setText("Facturada:");

        jLabel4.setText("Cliente:");

        jLabel5.setText("Peso Total (GR):");

        jLabel6.setText("Total Neto $:");

        jLabel7.setText("Descuento $:");

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel8.setText("$");

        vendedor.setText("---");

        facturada.setText("---");

        cliente.setText("---");

        peso.setText("----");

        neto.setText("---");

        descuento.setText("---");

        total.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        total.setText("---");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(peso))
                            .addComponent(cliente)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel8)
                                        .addComponent(jLabel7)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(neto)
                                    .addComponent(total)
                                    .addComponent(descuento, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(76, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(vendedor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(facturada)
                        .addGap(18, 18, 18))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(vendedor)
                    .addComponent(facturada))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cliente)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(peso))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(neto))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(descuento))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(total))
                .addGap(0, 9, Short.MAX_VALUE))
        );

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Cantidad", "Nombre", "Descuento", "P-Unit", "Importe", "Peso"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jButton4.setText("Actualizar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(26, 26, 26)
                                .addComponent(jButton4)
                                .addGap(0, 236, Short.MAX_VALUE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 10, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void setIconImage(Image image) {
       // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
 

    class LimitadorCaracteres extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        @Override
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!Character.isDigit(arg1.charAt(i))) {
                    return;
                }
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        cargarDatos();
// TODO add your handling code here:
    }//GEN-LAST:event_jTextField1KeyReleased

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        seleccion();
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked
    void seleccion() {
        ResultSet otro;
        String nombre = null;
        int row = jTable1.getSelectedRow();
        if (row != -1) {
            dtm = (DefaultTableModel) this.jTable2.getModel();
            dtm.setRowCount(0);
            ArrayList<Object[]> data = new ArrayList<>();
            Object[] rows = new Object[jTable2.getColumnCount()];
            try {
                String codigo, fac;
                int idCliente, cantidad;
                codigo = String.valueOf(jTable1.getValueAt(row, 0));
                ps = (PreparedStatement) cn.prepareStatement("select sum(cantidad*productos.peso),sum(cantidad*preciovendido)  from detalleventa join productos on productos.id_producto = detalleventa.id_producto where folio =" + codigo+" and detalleventa.preciovendido>0");
                rs = ps.executeQuery();
                rs.next();
                peso.setText(rs.getString(1));
                neto.setText(rs.getString(2));
                ps = (PreparedStatement) cn.prepareStatement("select preciovendido from detalleventa where folio =" + codigo + " and preciovendido < 0");
                rs = ps.executeQuery();
                descuento.setText("0.00");
                if (rs.next()) {
                    descuento.setText(rs.getString(1));
                }
                total.setText(String.valueOf(Float.parseFloat(neto.getText())+Float.parseFloat(descuento.getText())));
                ps = (PreparedStatement) cn.prepareStatement("select * from factura where id_ventap =" + codigo);
                rs = ps.executeQuery();
                fac = (rs.next()) ? "SI" : "NO";
                facturada.setText(fac);
                ps = (PreparedStatement) cn.prepareStatement("select id_cliente,id_usuario from venta where folio =" + codigo);
                rs = ps.executeQuery();
                rs.next();
                idUsuario = rs.getInt(2);
                idCliente = rs.getInt(1);
                ps = (PreparedStatement) cn.prepareStatement("Select nombre from personas where id_persona = " + idUsuario);
                rs = ps.executeQuery();
                rs.next();
                vendedor.setText(rs.getString(1));
                ps = (PreparedStatement) cn.prepareStatement("Select nombre, paterno, materno from personas where id_persona = " + idCliente);
                rs = ps.executeQuery();
                rs.next();
                cliente.setText(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));

                //cargamos productos
                ps = (PreparedStatement) cn.prepareStatement("Select cantidad,modo,preciovendido,id_producto,preciocompra,idetalle from detalleventa where folio = " + codigo);
                rs = ps.executeQuery();
                while (rs.next()) {
                    PreparedStatement pn;
                    ResultSet rm;
                    if (rs.getInt("id_producto") == -2) {
                        pn = (PreparedStatement) cn.prepareStatement("select nombre from otros where detalle_venta = ?");
                        pn.setInt(1, rs.getInt("idetalle"));
                        rm = pn.executeQuery();
                        rm.next();
                        nombre = rm.getString("nombre");
                    }
                    pn = (PreparedStatement) cn.prepareStatement("select nombre,peso from productos where id_producto = " + rs.getString("id_producto"));
                    rm = pn.executeQuery();
                    rm.next();
                    if (rs.getInt("id_producto") != -2) {
                        nombre = rm.getString("nombre");
                    }
                    cantidad = rs.getInt("cantidad");
                    rows[0] = rs.getString("id_producto");
                    rows[1] = cantidad;
                    rows[3] = rs.getString("modo");
                    rows[4] = rs.getString("preciovendido");
                    rows[5] = cantidad * rs.getFloat("preciovendido");
                    rows[2] = nombre;
                    rows[6] = rm.getInt("peso") * cantidad;
                    data.add(rows);



                    dtm.addRow(data.get(0));
                }
                data.clear();
            } catch (SQLException ex) {
                                 Logger.getLogger(ventas.class.getName()).log(Level.SEVERE, null, ex);
            }
            //cargar datos al jTable2
        }
    }
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        cargarDatos();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyReleased
        seleccion();        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1KeyReleased

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void cancelarV() {
        int codigo;
        int row = jTable1.getSelectedRow();
        codigo = (int) (jTable1.getValueAt(row, 0));
        try {
           // ps = (PreparedStatement) cn.prepareStatement("DELETE a.*, b.* FROM venta as a, detalleventa as b WHERE a.folio = b.folio AND a.folio = ?");
            ps = (PreparedStatement) cn.prepareStatement("DELETE FROM venta WHERE folio = ?");
            ps.setInt(1, codigo);
            ps.execute();
            // TODO add your handling code here:
        } catch (SQLException ex) {
            Logger.getLogger(ventas.class.getName()).log(Level.SEVERE, null, ex);
        }
        cargarDatos();
        DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
    model.setRowCount(0);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel cliente;
    private javax.swing.JLabel descuento;
    private javax.swing.JLabel facturada;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JLabel neto;
    private javax.swing.JLabel peso;
    private javax.swing.JLabel total;
    private javax.swing.JLabel vendedor;
    // End of variables declaration//GEN-END:variables
}
